library(survey)
library(dplyr)
library(ggplot2)
library(gridExtra)

# Creating Figure 6.3

# Wave 2
summary(factor(df$Q36))
summary(factor(df$P_ASSIGN5))

# Create binary for vote for Trump (2)
summary(factor(df$Q36))
df$Q36T[df$Q36 < 77] <- 0
df$Q36T[df$Q36 == 2] <- 1
summary(factor(df$Q36T))

# Create new variables for assigned condition
df2 <- df
# Mil biden
df2$PA5_mb[df2$P_ASSIGN5 == 1] <- 0
df2$PA5_mb[df2$P_ASSIGN5 == 2] <- 1

# Mil trump
df2$PA5_mt[df2$P_ASSIGN5 == 1] <- 0
df2$PA5_mt[df2$P_ASSIGN5 == 3] <- 1

# Gen Biden
df2$PA5_gb[df2$P_ASSIGN5 == 1] <- 0
df2$PA5_gb[df2$P_ASSIGN5 == 4] <- 1

# Gen Trump
df2$PA5_gt[df2$P_ASSIGN5 == 1] <- 0
df2$PA5_gt[df2$P_ASSIGN5 == 5] <- 1


w2_design <-
  svydesign(
    id = ~ 1,
    weights = ~ weight2,
    data = df2
  )


# Wave 2
# P_ASSIGN5 == 2 BIDEN
w2mb <- svyttest(Q36T~PA5_mb, w2_design)

# P_ASSIGN5 == 3 TRUMP
w2mt <- svyttest(Q36T~PA5_mt, w2_design)

# P_ASSIGN5 == 4 Generals BIDEN
w2gb <- svyttest(Q36T~PA5_gb, w2_design)

# P_ASSIGN5 == 5 Generals TRUMP
w2gt <- svyttest(Q36T~PA5_gt, w2_design)


# Wave 2
pt.est2 <- c(w2mb$estimate, w2mt$estimate, w2gb$estimate, w2gt$estimate)
ci.low2 <- c(w2mb$conf.int[1],w2mt$conf.int[1], w2gb$conf.int[1],w2gt$conf.int[1])
ci.high2 <- c(w2mb$conf.int[2],w2mt$conf.int[2], w2gb$conf.int[2],w2gt$conf.int[2])
plot.labs <- c('Military:\nBiden','Military:\nTrump','Generals:\nBiden','Generals:\nTrump')
df.plot2 <- data.frame(Treatment=plot.labs, estimate=pt.est2, 
                       lower=ci.low2, upper=ci.high2)
df.plot2$Treatment <- factor(df.plot2$Treatment, levels = plot.labs)

plot_w2 <- ggplot()+
  geom_pointrange(data=df.plot2, 
                  mapping = aes(x=Treatment,
                                y=estimate,
                                ymin=lower,
                                ymax=upper),
                  size = 0.5, color = 'black')+
  geom_hline(yintercept = 0, color = "red")+
  ylim(-.2,.2)+
  ylab("Difference in Means from Control Condition")+
  xlab("Treatment Condition")+
  ggtitle(label="Wave 2")+
  theme_bw()

